﻿using Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Common;
using Microsoft.SqlServer.Server;
using Web.Areas.Mobile.Lib;
using Web.Lib;

namespace Web.Areas.Mobile.Controllers
{
    public class UserController : BaseController
    {
        public ActionResult LogOut()
        {
            MobileAccount.LogOut();
            return View("SystemError");
        }

        /// <summary>
        /// 服务号授权
        /// </summary>
        /// <param name="openid"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public ActionResult Auth(string openid, string redirectUrl)
        {
            var queryParams = GenerateQuerString();

            if (string.IsNullOrWhiteSpace(redirectUrl))
            {
                redirectUrl = "/mobile/user/businesscard";
            }

            if (MobileAccount.ID > 0)
            {
                return Redirect(GenerateUrl(redirectUrl.Replace("_", "/"), queryParams));
            }

            if (!string.IsNullOrWhiteSpace(openid))
            {
                //保存至浏览器cookie
                new MobileAccount().LogOn(openid);

                return Redirect(GenerateUrl(redirectUrl.Replace("_", "/"), queryParams));
            }
            string appid, appsecret;
            new Admin.Lib.Site().GetAppConfig(out appid, out appsecret);

            var redirectUri = eDoctor.SDK.WeChat.WebPage.Call.authorize(appid, Common.UrlHelper.HostUrl + "/mobile/user/oauth?" + queryParams, "QAZEDCTGB");

            if (!string.IsNullOrWhiteSpace(redirectUri))
            {
                return Redirect(redirectUri);
            }
            else
            {
                return Redirect("/mobile/home/OAuthError?id=1");
            }
        }

        private string GenerateUrl(string url, string queryParams)
        {
            return url + (url.IndexOf("?") < 0 ? "?" : "&") + queryParams;
        }

        private string GenerateUrl(string url, List<string> queryParams)
        {
            return url + (url.IndexOf("?") < 0 ? "?" : "&") + string.Join("&", queryParams);
        }

        private string GenerateQuerString()
        {
            var queryParams = new List<string>();
            var qs = Request.QueryString;
            if (qs.HasKeys())
            {
                foreach (string ck in qs.Keys)
                {
                    if (ck.ToLower() != "userid".ToLower() && ck.ToLower() != "openid".ToLower())
                    {
                        queryParams.Add(ck + "=" + qs[ck]);
                    }
                }
            }

            return string.Join("&", queryParams);
        }

        /// <summary>
        /// 授权回调
        /// </summary>
        /// <param name="code"></param>
        /// <param name="state"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public ActionResult OAuth(string code, string state, string redirectUrl)
        {
            string appid, appsecret;
            if (new Admin.Lib.Site().GetAppConfig(out appid, out appsecret))
            {
                //通过code换取网页授权access_token
                var webtoken = eDoctor.SDK.WeChat.WebPage.Call.access_token(appid, appsecret, code);

                //判断授权是否成功
                if (webtoken == null || string.IsNullOrEmpty(webtoken.openid))
                {
                    return Redirect("/mobile/home/OAuthError?id=2");
                }

                //保存至浏览器cookie
                var r = new MobileAccount().LogOn(webtoken.openid);

                if (string.IsNullOrWhiteSpace(redirectUrl))
                {
                    redirectUrl = "/mobile/user/businesscard";
                }

                //自带参数
                var querystring = string.Empty;
                foreach (string key in Request.QueryString.Keys)
                {
                    if (key != "code" && key != "state" && key.ToLower() != "redirecturl")
                    {
                        querystring += "&" + key + "=" + Request.QueryString[key];
                    }
                }

                return Redirect(redirectUrl.Replace("_", "/") + (redirectUrl.IndexOf("?") < 0 ? "?" : "&") + querystring);
            }
            else
            {
                return Redirect("~/error");
            }
        }

        /// <summary>
        /// 企业号授权
        /// </summary>
        /// <param name="userid"></param>
        /// <param name="redirectUrl"></param>
        /// <returns></returns>
        public ActionResult CorpAuth(string userid, string openid, string redirectUrl)
        {
            var queryParams1 = GenerateQuerString();

            if (string.IsNullOrWhiteSpace(userid))
            {
                return Redirect("/mobile/user/auth?" + queryParams1);
            }

            userid = EncryptionHelper.Base64Helper.Decrypt(userid);

            var userLogic = new usersLogic();
            var user = userLogic.Getusers(new users { userid = userid });
            if (user == null)
            {
                var cu = new CorpHelper().GetCorpUserDetail(userid);
                if (cu == null)
                {
                    return Redirect("/mobile/home/CorpAuthError");
                }
                else
                {
                    var dbUser = new users
                    {
                        createdate = DateTime.Now,
                        createuserid = 0,
                        sn = Guid.NewGuid(),
                        status = (int)UserStatus.Normal,
                        userid = userid,
                        realname = (!string.IsNullOrWhiteSpace(cu.NAME) ? cu.NAME : (cu.FIRST_NAME + " " + cu.LAST_NAME)),
                        mobile = cu.MOBILE,
                        sex = cu.GENDER,
                        email = cu.UEMAIL,
                        ou_level_2 = cu.OU_LEVEL2_DESC,
                        postion = cu.POSITION_TITLE_CN,
                        company = cu.COMPANY_NAME,
                        province = cu.PROVINCE,
                        city = cu.CITY,
                        tag = cu.TAG,
                        avatar = ("http://ea.astrazeneca.com/" + cu.AVATAR)
                    };

                    var cr = GenerateUserCard(dbUser);
                    var uid = userLogic.Create(dbUser);
                }
            }

            new MobileAccount().LogOn(userid);

            if (string.IsNullOrWhiteSpace(redirectUrl))
            {
                redirectUrl = "/mobile/user/usercard";
            }

            var queryParams = new List<string>();
            var qs = System.Web.HttpContext.Current.Request.QueryString;
            if (qs.HasKeys())
            {
                foreach (string ck in qs.Keys)
                {
                    if (ck.ToLower() != "redirecturl".ToLower())
                    {
                        queryParams.Add(ck + "=" + qs[ck]);
                    }
                }
            }

            return Redirect(GenerateUrl(redirectUrl.Replace("_", "/"), queryParams));
            //return Redirect(redirectUrl.Replace("_", "/"));
        }

        #region 完善个人资料
        public ActionResult BusinessCard()
        {
            usersLogic ul = new usersLogic();
            var user = ul.Getusers(new users() { id = MobileAccount.ID }) ?? new users() { openid = MobileAccount.OpenID };
            if (user.status == (int)UserStatus.Normal)
            {
                return RedirectToAction("EditUserInfo");
            }
            else
            {
                return View(user);
            }
        }

        [HttpPost]
        public ActionResult BusinessCard(users user)
        {
            try
            {
                usersLogic ul = new usersLogic();
                if (string.IsNullOrEmpty(user.mobile))
                {
                    return ErrorMsg("手机号码不能为空！");
                }
                users dbModel = null;
                // 1. 首先根据openid查找用户（通过扫描会议二维码关注的用户）
                if (!string.IsNullOrWhiteSpace(user.openid))
                {
                    dbModel = ul.Getusers(new users { openid = user.openid });
                }
                var muLogic = new meeting_userLogic();
                // 2. 会议名单中的用户
                if (dbModel == null)
                {
                    // 1. 首先查询用户表中是否有相同手机号码的用户
                    var mobileUser = ul.Getusers(new users() { mobile = user.mobile });
                    if (mobileUser != null && mobileUser.openid != user.openid)
                    {
                        return ErrorMsg("此手机号码已被其他用户认证，请确认！");
                    }
                    // 2. 查询导入名单中是否存在此手机号码
                    var meetingUser = muLogic.Getmeeting_user(new meeting_user { mobile = user.mobile });
                    if (meetingUser != null && meetingUser.userid > 0)
                    {
                        return ErrorMsg("此手机号码已被其他用户认证，请确认！");
                    }

                    user.createdate = DateTime.Now;
                    user.status = (int)UserStatus.Normal;
                    user.sn = Guid.NewGuid();

                    var cr = GenerateUserCard(user);
                    if (!cr)
                    {
                        return ErrorMsg("您的个人名片生成失败，请稍后再试！");
                    }

                    ul.Add(user);



                    if (meetingUser != null)
                    {
                        var dbUser = ul.Getusers(new users { sn = user.sn }) ?? new users();

                        muLogic.UpdateMeetingUser(dbUser.mobile, dbUser.id);
                    }
                }
                else
                {
                    var mobileUser = ul.Getusers(new users() { mobile = user.mobile });
                    if (mobileUser != null && mobileUser.openid != user.openid)
                    {
                        return ErrorMsg("此手机号码已被其他用户认证，请确认！");
                    }

                    dbModel.realname = user.realname;
                    dbModel.mobile = user.mobile;
                    dbModel.modifydate = DateTime.Now;
                    dbModel.openid = user.openid;
                    dbModel.province = user.province;
                    dbModel.city = user.city;
                    dbModel.hospital = user.hospital;
                    dbModel.postion = user.postion;
                    dbModel.email = user.email;
                    dbModel.status = (int)UserStatus.Normal;
                    dbModel.company = user.company;


                    ul.Update(dbModel);

                    muLogic.UpdateMeetingUser(dbModel.mobile, dbModel.id);
                }

                //发送客服消息
                var token = new Admin.Lib.Site().GetAccessToken();
                var result = new eDoctor.SDK.WeChat.Call(token).SendCustom<eDoctor.SDK.WeChat.Request.CustomText>(new eDoctor.SDK.WeChat.Request.CustomText
                {
                    touser = user.openid,
                    content = string.Format("恭喜您，认证成功！", user.realname)
                });

                new MobileAccount().LogOn(user.openid);

                return SuccessMsg();
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }

        private bool GenerateUserCard(users user)
        {
            // 前台生成个人名片
            return true;
            /*
            try
            {
                Bitmap logo = null;
                if (user.type == (int)UserType.Internal)
                {
                    var localPath = System.Web.HttpContext.Current.Server.MapPath("~") +
                                    "/areas/mobile/html/images/azlogo.jpg";//"azlogo.png";
                    logo = new Bitmap(localPath);
                }
                //todo: 生成个人名片
                var vcard = @"BEGIN:VCARD 
N:赵晓赟;zxy;;; 
FN: zxy 赵晓赟 
TITLE:R&D - 研发经理 
ADR;WORK:;;上海市天山路210号;;;; 
ORG:上海翼得营销策划有限公司 
TEL;CELL,VOICE:15921322542 
TEL;WORK,VOICE:021-31319364 
URL;WORK:http://www.edoctor.cn 
EMAIL;zora.zhao@edoctor.cn
HOME:www.edoctor.cn 
KCODE:zora.zhao 
SN:72BAA357-8142-4A16-98D1-2FFF81725CA1
END:VCARD";
                var card = QrcodeHelper.CreateQrCode(vcard, null, null, logo);
                var path = "/Upload/UserCard/";
                var fileName = user.sn.ToString("N") + ".jpg";
                var filePath = System.Web.HttpContext.Current.Server.MapPath("~") + path + fileName;
                ImageCodecInfo imageCodecInfo = ImageHelper.GetEncoderInfo(ImageFormat.Jpeg);
                card.Save(filePath, imageCodecInfo, null);
                user.cardurl = path + fileName;

                return true;
            }
            catch (Exception e)
            {
                Logs.Execute("GenerateUserCard：" + e.Message);
                //todo: 二维码生成失败处理
                return false;
            }
              */
        }

        public ActionResult UserCard()
        {
            if (MobileAccount.ID == 0)
            {
                return RedirectToAction("BusinessCard");
            }
            usersLogic ul = new usersLogic();
            var user = ul.Getusers(new users() { id = MobileAccount.ID });

            //未认证
            if (user.status == (int)UserStatus.None)
            {
                return RedirectToAction("BusinessCard");
            }

            return View(user);
        }

        #endregion

        #region 个人中心
        public ActionResult EditUserInfo()
        {
            usersLogic ul = new usersLogic();
            var user = ul.Getusers(new users() { id = MobileAccount.ID });
            if (user == null)
            {
                return RedirectToAction("BusinessCard");
            }
            return View(user);
        }

        [HttpPost]
        public ActionResult EditUserInfo(users user)
        {
            try
            {
                usersLogic ul = new usersLogic();
                meeting_userLogic muLogic = new meeting_userLogic();

                //1.先判断修改后的手机号与原来的手机号是否相同
                var userByOpendID = ul.Getusers(new users() { openid = user.openid });
                if (user.mobile != userByOpendID.mobile)
                {
                    // 2. 如果不相同，则判断新手机号码有没有被使用
                    var userByNewMobile = ul.Getusers(new users() { mobile = user.mobile });
                    var meetingUserByNewMobiles = muLogic.Getmeeting_users(new meeting_user { mobile = user.mobile });
                    if (userByNewMobile != null)
                    {
                        if (userByNewMobile.openid != userByOpendID.openid)
                        {
                            return ErrorMsg("此手机号码已被其他用户认证，请确认！");
                        }
                    }
                    if (meetingUserByNewMobiles.Count > 0)
                    {
                        if (meetingUserByNewMobiles.Any(o => o.userid > 0 && o.userid != user.id))
                        {
                            return ErrorMsg("此手机号码已被其他用户认证，请确认！");
                        }
                        else
                        {
                            foreach (var item in meetingUserByNewMobiles)
                            {
                                item.modifydate = DateTime.Now;
                                muLogic.Update(item);
                            }
                        }
                    }
                    else
                    {
                        //3. 先将老的手机号码关联的meeting_user的userid置为0
                        var meetingUserByOldMobiles = muLogic.Getmeeting_users(new meeting_user() { mobile = userByOpendID.mobile });
                        foreach (meeting_user item in meetingUserByOldMobiles)
                        {
                            item.userid = 0;
                        }
                        muLogic.Update(meetingUserByOldMobiles);
                    }
                }
                ul.Update(user);
                return SuccessMsg();
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }
        #endregion

        [HttpPost]
        public ActionResult Register(users user, string code)
        {
            try
            {
                var sms = System.Web.HttpContext.Current.Session["SMS"];
                if (sms == null)
                {
                    return ErrorMsg("验证码已过期，请重新发送");
                }
                if (code != sms.ToString())
                {
                    return ErrorMsg("验证码错误！");
                }
                usersLogic ul = new usersLogic();
                var dbUserByMobile = ul.Getusers(new users() { mobile = user.mobile });
                if (dbUserByMobile != null && dbUserByMobile.openid != user.openid)
                {
                    return ErrorMsg("手机号码已被使用，请确认！");
                }
                if (dbUserByMobile != null && dbUserByMobile.openid == user.openid)
                {
                    MobileAccount.LogOut();
                    return RedirectToAction("Auth", new { openid = user.openid, userid = "", redirectUrl = "_mobile_user_edituserinfo" });
                }
                else
                {
                    user.createdate = DateTime.Now;
                    user.status = (int)UserStatus.None;
                    user.sn = Guid.NewGuid();
                    var id = ul.Create(user);

                    if (id > 0)
                    {
                        var newDbUser = ul.Getusers(new users() { id = id });
                        MobileAccount.LogOut();
                        new MobileAccount().LogOn(user.openid);
                        return SuccessMsg("提交成功！");
                    }
                    else
                    {
                        return ErrorMsg("提交失败！");
                    }
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }
        [HttpPost]
        public ActionResult GetAuthCode(string mobile)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(mobile))
                {
                    return ErrorMsg("请填写手机号码！");
                }
                else
                {
                    string sms = Character.RandomString("num", 6);
                    //SMSHelper.Send(mobile, "你的注册验证码为：" + sms, "爱呼吸");
                    SMSHelper.UCPaasSend(EnumHelper.SendTemplate.IdentifyingCode, mobile, sms);

                    System.Web.HttpContext.Current.Session["SMS"] = sms;

                    return SuccessMsg("验证码已通过短信发送到您的手机，请注意查收！");
                }
            }
            catch (Exception e)
            {
                return ErrorMsg(e.Message);
            }
        }

        /// <summary>
        /// 自定义验证
        /// </summary>
        public ActionResult CustormAuth(Guid msn)
        {
            try
            {
                usersLogic ul = new usersLogic();
                meetingLogic ml = new meetingLogic();
                var meeting = ml.Getmeeting(new meeting() { sn = msn });
                ViewBag.Meeting = meeting;
                var user = ul.Getusers(new users() { id = MobileAccount.ID }) ?? new users() { openid = MobileAccount.OpenID };
                return View(user);
            }
            catch (Exception e)
            {
                return Content(e.Message + "||" + e.Source);
            }
        }
    }
}
